package com.study.shiro.config;

import com.study.shiro.entity.Permission;
import com.study.shiro.entity.User;
import com.study.shiro.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义 realm
 * @author huang guang yue
 * @version v1.0.0
 * @date 2021 2021/3/17 16:42
 */
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    /**
     * 鉴权认证，缓存可以在 service 层，也可以使用 shiro-redis 插件
     *
     * 当前使用 shiro-redis。如果不使用 shiro-redis：
     *      1，直接从 PrincipalCollection 获取用户名：String username = (String) principals.getPrimaryPrincipal();
     *      2，service 层加入缓存
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User cacheUser = (User) principals.getPrimaryPrincipal();
        User user = userService.listRoleAndPermsByUsername(cacheUser.getName());
        // 当前用户角色名
        List<String> roles = new ArrayList<>();
        // 当前用户权限
        List<String> perms = new ArrayList<>();
        user.getRoles().forEach( item -> {
            roles.add(item.getName());
            List<String> collect = item.getPerms().stream().map(Permission::getName).collect(Collectors.toList());
            perms.addAll(collect);
        });

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    /**
     * 登陆认证
     *
     * 当前使用 shiro-redis。如果不使用，传入的参数不一样（一个是 username，一个是 user）
     * @return new SimpleAuthenticationInfo(username, user.getPassword(), this.getClass().getName());
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String username = (String) token.getPrincipal();
        // 获取该用户的密码
        User user = userService.selectByName(username);
        if (user == null || StringUtils.isEmpty(user.getPassword())){
            return null;
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
    }

}
